package com.house.tgroup.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.house.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.house.tgroup.dao.GroupDao;
import com.house.tgroup.entity.GroupEntity;
import com.house.tgroup.service.GroupService;


@Service("groupService")
@SuppressWarnings("all")
public class GroupServiceImpl extends ServiceImpl<GroupDao, GroupEntity> implements GroupService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private GroupDao groupDao;
    @Override
    public R getlist(String name) {
        //页面加载先去redis查询
        String tglist = redisTemplate.opsForValue().get("tglist");
        if (tglist!=null){
            //如果redis里有，判断传入参数是否为空
            System.out.println("缓存命中");
            List<GroupEntity> list = JSON.parseObject(tglist, new TypeReference<List<GroupEntity>>() {
            });
            //传入参数不为空 再进行比较，最后返回glist集合
            if (StringUtils.isNotEmpty(name)){
                ArrayList<GroupEntity> glist = new ArrayList<>();
                for (GroupEntity groupEntity : list) {
                    if (groupEntity.getGroupName().contains(name)){
                        glist.add(groupEntity);
                    }

                }
                return R.ok().put("list",glist);
                //如果传参为空，直接返回list集合
            }
            return R.ok().put("list",list);

        }else{
            List<GroupEntity>list=groupDao.getlist(name);
            System.out.println("数据库查询");
            //放入redis 有效时间为 60秒
            redisTemplate.opsForValue().set("tglist",JSON.toJSONString(list),60, TimeUnit.SECONDS);
            return R.ok().put("list",list);
        }
    }

}